/*
 * Copyright 2013-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.kubernetes.client.discovery;

import java.util.List;
import java.util.Map;
import java.util.Set;

import io.kubernetes.client.informer.cache.Cache;
import io.kubernetes.client.informer.cache.Lister;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.CoreV1EndpointPortBuilder;
import io.kubernetes.client.openapi.models.V1EndpointAddressBuilder;
import io.kubernetes.client.openapi.models.V1EndpointSubsetBuilder;
import io.kubernetes.client.openapi.models.V1Endpoints;
import io.kubernetes.client.openapi.models.V1EndpointsBuilder;
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceBuilder;
import io.kubernetes.client.openapi.models.V1ServicePortBuilder;
import io.kubernetes.client.openapi.models.V1ServiceSpecBuilder;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;

/**
 * @author wind57
 */
class KubernetesClientDiscoveryClientServiceWithoutPortNameTests {

	private static final SharedInformerStub<V1Service> SERVICE_SHARED_INFORMER_STUB = new SharedInformerStub<>();

	private static final SharedInformerStub<V1Endpoints> ENDPOINTS_SHARED_INFORMER_STUB = new SharedInformerStub<>();

	private static CoreV1Api coreV1Api;

	private static SharedInformerFactoryStub sharedInformerFactoryStub;

	private static final String NAMESPACE = "spring-k8s";

	private Cache<V1Service> servicesCache;

	private Lister<V1Service> servicesLister;

	private Cache<V1Endpoints> endpointsCache;

	private Lister<V1Endpoints> endpointsLister;

	@BeforeAll
	static void beforeAll() {
		coreV1Api = Mockito.mock(CoreV1Api.class);
		ApiClient apiClient = Mockito.mock(ApiClient.class);
		Mockito.when(coreV1Api.getApiClient()).thenReturn(apiClient);

		sharedInformerFactoryStub = new SharedInformerFactoryStub(apiClient);
	}

	@BeforeEach
	void beforeEach() {
		servicesCache = new Cache<>();
		servicesLister = new Lister<>(servicesCache);

		endpointsCache = new Cache<>();
		endpointsLister = new Lister<>(endpointsCache);
	}

	@Test
	void testDiscoveryWithoutAServicePortName() {

		V1Endpoints endpoints = new V1EndpointsBuilder()
			.withSubsets(new V1EndpointSubsetBuilder().withPorts(new CoreV1EndpointPortBuilder().withPort(8080).build())
				.withAddresses(new V1EndpointAddressBuilder().withIp("127.0.0.1").build())
				.build())
			.withMetadata(new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build())
			.build();
		endpointsCache.add(endpoints);

		V1Service service = new V1ServiceBuilder()
			.withSpec(new V1ServiceSpecBuilder().withPorts(new V1ServicePortBuilder().withPort(8080).build()).build())
			.withMetadata(new V1ObjectMetaBuilder().withName("no-port-name-service").withNamespace(NAMESPACE).build())
			.withSpec(new V1ServiceSpecBuilder().withType("ClusterIP").build())
			.build();
		servicesCache.add(service);

		KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, Set.of(NAMESPACE),
				true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0,
				true, false, null);
		KubernetesClientInformerDiscoveryClient discoveryClient = new KubernetesClientInformerDiscoveryClient(
				List.of(sharedInformerFactoryStub), List.of(servicesLister), List.of(endpointsLister),
				List.of(SERVICE_SHARED_INFORMER_STUB), List.of(ENDPOINTS_SHARED_INFORMER_STUB), properties, coreV1Api,
				x -> true);

		List<ServiceInstance> serviceInstances = discoveryClient.getInstances("no-port-name-service");
		Assertions.assertThat(serviceInstances.size()).isEqualTo(1);
		Assertions.assertThat(serviceInstances.get(0).getMetadata())
			.isEqualTo(Map.of("port.<unset>", "8080", "k8s_namespace", "spring-k8s", "type", "ClusterIP"));
	}

}
